package com.etlmaster.datax.plugins.writer.vfswriter;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder;
public class VFSFileFinder {

	
	public static FileObject resolveFile(String baseDir) throws FileSystemException {
		

		FileObject fo = null;
		if (baseDir.startsWith("sftp")) {
			StandardFileSystemManager mgr = getStandardFileSystemManager();
			FileSystemOptions opts = new FileSystemOptions();
			SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
					opts, "no");
			SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts,
					false);
			SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, Integer.MAX_VALUE);
			fo = mgr.resolveFile(baseDir, opts);
		} else {
			FileSystemManager mgr=VFS.getManager();
			FileSystemOptions opts = new FileSystemOptions();
			FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
			FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
			fo = mgr.resolveFile(baseDir,opts);
		}

		return fo;
	}
	public static void closeFile(FileObject fo){
		try {
			fo.close();
		} catch (FileSystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static StandardFileSystemManager getStandardFileSystemManager()
			throws FileSystemException {
		StandardFileSystemManager mgr = (StandardFileSystemManager) VFS
				.getManager();
		synchronized (mgr) {
			if (!ArrayUtils.contains(mgr.getSchemes(), "hdfs")) {

			}
			/* mgr.addProvider("hdfs", new HDFSFileProvider()); */
		}
		return mgr;
	}

}
